import Vue from "vue";
import VueRouter from "vue-router";
import Layout from "../Layout/Layout.vue";
import Login from "../views/Login.vue";
import Student from "../views/Student/Student.vue";
import Home from "../views/Home/Home.vue";
import Course from "../views/Course/Course.vue";
import Finance from "../views/Finance/Finance.vue";
import OrderForm from "../views/OrderForm/OrderForm.vue";
import Teacher from "../views/Teacher/Teacher.vue";
import LogAndReg from "../views/LogAndReg.vue";
import Register from "../views/Register.vue";

import { getToken } from "../utils/cookieUtils";

Vue.use(VueRouter);

const routes = [
  {
    path: "/",
    name: "Layout",
    component: Layout,
    redirect: "/login",
    children: [
      // 首页
      {
        path: "/home",
        name: "Home",
        component: Home,
      },
      // 学员
      {
        path: "/student",
        name: "Student",
        component: Student,
      },
      // 教师
      {
        path: "/teacher",
        name: "Teacher",
        component: Teacher,
      },
      // 课程
      {
        path: "/course",
        name: "Course",
        component: Course,
      },
      // 订单
      {
        path: "/orderform",
        name: "OrderForm",
        component: OrderForm,
      },
      // 财务
      {
        path: "/finance",
        name: "Finance",
        component: Finance,
      },
    ],
  },
  // 登录
  {
    path: "/logandreg",
    name: "LogAndReg",
    component: LogAndReg,
    redirect: "/login",
    children: [
      {
        path: "/login",
        name: "Login",
        component: Login,
      },
      {
        path: "/register",
        name: "Register",
        component: Register,
      },
    ],
  },
];
//解决vuerouter  3.0.7 以上版本带来的重复跳转bug
const originalPush = VueRouter.prototype.push;
VueRouter.prototype.push = function push(location, onResolve, onReject) {
  if (onResolve || onReject)
    return originalPush.call(this, location, onResolve, onReject);
  return originalPush.call(this, location).catch((err) => err);
};

const router = new VueRouter({
  routes,
  mode: "history",
});

const whiteList = ["/Login", "/login", "/register"]; //白名单
import vuex from "../store";
router.beforeEach((to, from, next) => {
  // to and from are both route objects. must call `next`.
  let token = getToken("token");
  vuex.state.route = to.path;
  //不包含在白名单中的路由
  if (token) {
    //已登录
    if (to.path == "/login" || to.path == "/Login") {
      next("/home");
    } else {
      next();
    }
  } else {
    //未登录
    if (!whiteList.includes(to.path)) {
      next("/login");
    } else {
      next();
    }
  }
});
//         先判断有没有白名单中
//            在白名单 直接放行  next() ['登陆页，找回密码 首页/']
//            没有  next('/login')
//      已经登录
//         判断/login
//            是login  直接重定向/首页
//            不是login  比如/user
//               发送请求  获取用户信息  主要获取角色信息
//               动态路由制作【动态菜单放入vuex】
export default router;
